package com.project2.service;

import com.project2.bean.bo.AdminConfigBo;
import com.project2.bean.po.MarketSystem;
import com.project2.bean.po.MarketSystemExample;
import com.project2.mapper.MarketSystemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: MH
 * @Date: 2022-08-12 18:02
 * @Description: 配置管理业务代码具体实现,前端需要的响应返回对象是键值对形式,
 *               所以使用HashMap作为返回对象
 */
@Service
public class ConfigServiceImpl implements ConfigService {

    @Autowired
    MarketSystemMapper marketSystemMapper;

    @Override
    public HashMap<String, String> getConfigs(MarketSystem marketSystem1) {
        List<MarketSystem> marketSystems = marketSystemMapper.selectByExample(null);
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        for (MarketSystem marketSystem : marketSystems) {
            stringStringHashMap.put(marketSystem.getKeyName(), marketSystem.getKeyValue());
        }
        return stringStringHashMap;
    }

    /**
    *@Author: MH
    *@date: 2022/8/17 21:15
    *@Description:修改配置的具体实现
    */
    @Override
    public void updateMallConfig(AdminConfigBo adminConfigBo) {
        Class<? extends AdminConfigBo> aClass = adminConfigBo.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();

        for (int i = 0; i <declaredFields .length ; i++) {
            Field declaredField = declaredFields[i];
            String name = declaredField.getName();
            String getMethodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            MarketSystemExample marketSystemExample = new MarketSystemExample();
            MarketSystemExample.Criteria criteria = marketSystemExample.createCriteria();
            criteria.andKeyNameEqualTo(name);
            MarketSystem marketSystem = new MarketSystem();
            String invoke = null;
            try {
                Method method = aClass.getMethod(getMethodName);
                invoke = (String) method.invoke(adminConfigBo);

            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            marketSystem.setKeyValue(invoke);
            marketSystemMapper.updateByExampleSelective(marketSystem,marketSystemExample);
        }
    }

}
